package com.java.basis.thread.n3.jiaoti;

import lombok.extern.slf4j.Slf4j;
import sun.security.jgss.spnego.NegTokenInit;

/**
 * wait/notify 实现多线程下交替输出
 * 线程1，输出a
 * 线程2，输出b
 * 线程3，输出c
 * 定义等待标记flag，
 *
 * @author wangning
 * @create 2022-01-25 10:27
 */
@Slf4j(topic = "c.Test01")
public class Test01 {
	public static void main(String[] args) {
		WaitNotify waitNotify = new WaitNotify(1, 5);
		new Thread(() -> {
			waitNotify.print("a", 1, 2);
		}).start();
		new Thread(() -> {
			waitNotify.print("b", 2, 3);
		}).start();
		new Thread(() -> {
			waitNotify.print("c", 3, 1);
		}).start();

	}

}

class WaitNotify {
	//等待标记
	private int flag;
	//循环次数
	private int loopNumber;

	public WaitNotify(int flag, int loopNumber) {
		this.flag = flag;
		this.loopNumber = loopNumber;
	}
	//打印
	public void print(String str, int waitFlag, int nextFlag) {
		for (int i = 0; i < loopNumber; i++) {
			synchronized (this) {
				while (flag != waitFlag) {
					try {
						this.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.print(str);
				flag = nextFlag;
				this.notifyAll();
			}
		}
	}
}
